<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
	<title>购物车</title>
	<link href="https://tcsc.oss-cn-hangzhou.aliyuncs.com/static/wechat/frame/mui/css/mui.min.css" rel="stylesheet" />
	<link href="https://tcsc.oss-cn-hangzhou.aliyuncs.com/static/wechat/css/other/all.css" rel="stylesheet" />
	<link href="https://tcsc.oss-cn-hangzhou.aliyuncs.com/static/wechat/css/other/app.css" rel="stylesheet" />
	<link href="https://tcsc.oss-cn-hangzhou.aliyuncs.com/static/wechat/font/iconfont.css" rel="stylesheet" />
</head>
<style type="text/css">
	.shopping_cart ul li .cart_top>span{
		background: url(/static/wechat/img/cart/checked1.png);
		 background-size: 100%;
	}
	.settlement p .catoption_header{
		background: url(/static/wechat/img/cart/checked1.png);
		 background-size: 100%;
	}
	.mui-numbox{
		height: 30px;
		padding: 0 30px;
		width: 92px;
		top:56px !important;
		right: 0 !important
	}
	.mui-numbox .mui-input-numbox, .mui-numbox .mui-numbox-input{
		width: 30px!important;
		padding: 0 0px!important;
	}
	.mui-numbox [class*=btn-numbox], .mui-numbox [class*=numbox-btn]{
		width: 30px;
	}
	html,body{
		height: 100%;
	}
	.noshopcar{height: calc(100vh - 50px);background: url('/static/wechat/img/noshopcar.png') no-repeat;background-size: 63%;background-position: center;
	display: {{if .info}}none{{else}}block{{end}}}
	.shopping_cart{display:{{if .info}}block{{else}}none{{end}};margin-top: 48px;}
	.settlement{display:{{if .info}}block{{else}}none{{end}};z-index:11;}
	.mui-slider-handle{width: 100%;}
	.noshopcar span.goto{position: absolute;bottom: 30%;padding:5px 10px;font-size: 15px;border:1px #ccc solid;border-radius: 5px;color: #aaa;left: calc(50% - 69px)}
	.shopping_cart h1{margin-top: 10px;background: #fff;line-height: 40px;height: 40px;padding-left: 10px;
		border-bottom: 1px solid #ddd}
	.shopping_cart h1:nth-of-type(1){margin-top: 0}
	/*.mui-table-view-cell:after{height: 0}*/
	.shopping_cart ul li{margin: 0}
	.brand-wrap {color: #666; padding-left: 10px;background-color: #fff;}
	.brand-wrap .brand-name {height: 32px;line-height: 32px;}
	.fold-wrap {color: #e54242;text-align: right;padding-right: 10px;line-height: 24px;}
	.fold-wrap .fold {margin-right: 10px;}
	.head {position: fixed;display: flex;justify-content: center;top: 0;left: 0;height: 40px;width: 100vw;line-height: 40px;border-bottom: 1px solid #ddd;color: #666;background-color: #fff;z-index: 11;}
	.head a {display:block;flex: 1;height: 100%;text-align: center;}
	.head .back {width: 45px;text-align: center;font-size: 18px;font-weight: 800;}
	.head a.on {color: #e54242;}
</style>
<body>
<div class="head">
	<div class="back iconfont icon-fanhui1" onclick="location = location.origin + '/mobile/index'"></div>
	<a {{if eq .sort ""}}class="on"{{else}}{{end}} href="/mobile/shopcar">综合</a>
	<a {{if eq .sort "time"}}class="on"{{else}}{{end}} href="/mobile/shopcar?sort=time">时间</a>
	<a {{if eq .sort "class"}}class="on"{{else}}{{end}} href="/mobile/shopcar?sort=class">类别</a>
</div>
<div class="shopping_cart">
	<!-- {{range .info}}
	<div>

		<h1>
			<span class="mui-icon iconfont fs-16">&#xe75f;</span> 
			{{if .shop}}
			{{.shop.name}}
			{{else}}
			{{$.system.name}}
			{{end}}
		</h1>
		<ul>
			{{range .shopcar}}
			<li class="pro_car mui-table-view-cell" id="{{.id}}">
				<div class="mui-slider-right mui-disabled">
					<a class="mui-btn mui-btn-red garbage" data-id="{{.id}}">删除</a>
				</div>
				<div class="mui-slider-handle">
					<div id="cart" class="cart_top">
						<span style="background-image: url('/static/wechat/img/cart/checked1.png');">
							<input class="selected" data-id="{{.id}}" type="checkbox" onclick="selected(this)" name="test">
						</span>
						<img src="{{.pathname}}" class="goto" href="/mobile/column/product_content?id={{.pid}}">
					</div>
					<div class="cart_box goto" href="/mobile/column/product_content?id={{.pid}}">
						<p class="overpl1"><span>{{.title}}</span></p>
						<p class="c-999">
							装箱数:{{.number}}<br>
							型号:{{.model}}
						</p>
						<div>
							是否可批发，是否满足批发数量
							<span>￥ <b class="bprice" id="pricem{{.id}}" data-id="{{.id}}">{{.pricem}}</b>/{{if eq .spec "1"}}件{{else}}箱{{end}}</span>
							<input class="j" type="hidden" value="{{.price}}">
						</div>
					</div>
					<span class="garbage" data-id="{{.id}}"><i class="mui-icon fr iconfont">&#xe7a1;</i></span>
					<div class="mui-numbox fr numb" data-numbox-min="1" data-numbox-max="999">
						<button class="mui-btn mui-btn-numbox-minus" type="button">-</button>
						<input data-id="{{.id}}" data-price="{{.price}}" data-isw="{{.isw}}" data-width="{{.width}}" data-length="{{.length}}" data-height="{{.height}}" class="mui-input-numbox numbox jg_val" type="number" value="{{.num}}" />
						<button class="mui-btn mui-btn-numbox-plus" type="button">+</button>
					</div>		
				</div>
			</li>

			{{end}}
		</ul>
	</div>
	{{end}} -->
</div>
<!-- <div class="scpic"></div> -->
<div class="settlement">
	<p class="fl wt-w70">
		<span class="catoption_header"><input id="asd" type="checkbox" name=""></span>
			全选
		<span class="fr tx-r" style="font-size: 14px;">
			总计:&yen;<b id="product_total">0.00</b> <span style="font-size: 12px;font-weight: 300;color: #666">(体积:<b id="product_tj">0.00</b>)</span>
		</span>
	</p>
	<p class="fr wt-w30">
		<!-- /wechat/paymoney -->
		<!-- <a id="sure"> -->
			<button id="btn">提交</button>
		<!-- </a> -->
	</p>
</div>
<div class="noshopcar">
	<span class="goto" href="/mobile/index">快去添加商品吧~</span>
</div>
<nav class="mui-bar mui-bar-tab">
    <a class="mui-tab-item" href="/mobile/index">
        <span class="mui-icon iconfont icon-home2"></span>
        <span class="mui-tab-label">首页</span>
    </a>
    <a class="mui-tab-item" href="/mobile/column">
        <span class="mui-icon iconfont icon-liebiao"></span>
        <span class="mui-tab-label">分类</span>
    </a>
    <!-- <a class="mui-tab-item" href="/mobile/active">
        <span class="mui-icon iconfont icon-tianmaohaoquan"></span>
        <span class="mui-tab-label">活动</span>
    </a> -->
    <a class="mui-tab-item mui-active" href="/mobile/shopcar">
        <span class="mui-icon iconfont icon-gouwucheman"></span>
        <span class="mui-tab-label">购物车</span>
    </a>
    <a class="mui-tab-item" href="/mobile/my">
		<span class="mui-icon iconfont icon-kefuyouxian"></span>
		<span class="mui-tab-label">我的</span>
	</a>
</nav>
<script src="https://tcsc.oss-cn-hangzhou.aliyuncs.com/static/wechat/js/other/app.js"></script>
<script type="text/javascript" src="https://tcsc.oss-cn-hangzhou.aliyuncs.com/static/wechat/frame/sui/js/SUI.js"></script>
<script src="https://tcsc.oss-cn-hangzhou.aliyuncs.com/static/wechat/frame/mui/js/mui.min.js"></script>
<script src="https://tcsc.oss-cn-hangzhou.aliyuncs.com/static/wechat/js/zepto.min.js"></script>
{{template "wechat/public/share.html" .}}
<script>
    mui.init({
        swipeBack:true //启用右滑关闭功能
    });
    //释放 nav 底部导航 a 链接
    mui('.mui-tab-item').each(function () {
        this.addEventListener('tap',function () {
            var url = this.getAttribute('href');
            window.location.href=url;
        })
    });
    mui('body').on('tap','.goto',function(){
    	if(this.getAttribute("href")){
    		window.location.href=this.getAttribute("href")
    	}
    })
</script>
<div class="mt-statistics">统计代码</div>
</body>
</html>
<script>
	const info = {{.info}}
	console.log(info)
	const sortType = {{.sort}}
	const f = {
		q: function (el) {
			return document.querySelector(el)
		},
		qa: function (el) {
			let els = Array.from(document.querySelectorAll(el)),
				i = 0;
			els.map(v => {
				v.index = i++
			})
			return els
		},
		some: function (str, arr) {
			return arr.some(function (v) { return v == str })
		},
		include: function (str, strs) {
			if (!strs) return false
			return this.some(str, strs.split(','))
		}
	}
	const systemName = {{.system.name}}
	console.log(systemName)
	function brandSort() {
		let arr = info.filter(function (v) {
			return v.gid == 0
		})[0]
			console.log(arr)
		if (!arr) return null
		let uid = arr.uid
		let resArr = arr.classify.map(function (v) {
			
			if(f.include(uid, v.uid) && v.fold) {
				v.isfold = true
			}
			v.product = []
			v.priceTotal = 0
			for (let product of arr.shopcar) {
				if (f.include(product.bid, v.bid)) {
					v.product.push(product)
					v.isPro = true
				}else{
					// console.log(product)
				}
			}
			v.priceTotal = v.priceTotal.toFixed(2)
			return v
		})
		return resArr
	}

	function sort(info, type) {		//整体排序
		for (let v of info) {
			if (!type) return
			if (type == "class") {
				v.shopcar.sort(function (a, b) {
					return a.cid - b.cid
				})
			} else if (type == "time") {
				v.shopcar.sort(function (a, b) {
					if (a.addtime > b.addtime) {
						return -1
					} else {
						return 1
					}
				})
			}
		}
	}

	sort(info, sortType)
	console.log(info)
	function nodes(info) {	
		let container = ""
		for (let v of info) {
			console.log(v)
			container += `<div>
				<h1>
					<span class="mui-icon iconfont fs-16">&#xe75f;</span>
					${v.gid == 0 ? systemName : v.shop.name}
				</h1>
				<ul>
			`
			if (v.gid != 0) {
				for (let p of v.shopcar) {
					container += product(p)
				}
			} else {
				let brand = brandSort()
				// console.log("brand------")
				// console.log(brand)
				if (brand) {
					for (let b of brand) {
						if (b.isPro) {
							container += `<div class="brand-wrap" data-fold="${b.fold}">
								<div class="brand-name">${b.name}</div>`
							for (let p of b.product) {
								container += product(p)
							}
							container += `<div class="fold-wrap">
											<span class="fold">${b.isfold ? '合伙人额外折扣:'+b.fold/10+'折' : '' }</span>
											<span class="price-total" data-fold="${b.isfold ? b.fold : 100}">合计:0.00</span>	
										  </div>
								</div>`
						}
					}
				}
			}
			container += `	
				</ul>
			</div>`
		}
		f.q('.shopping_cart').innerHTML = container
	}

	function product(p) {
		return `<li class="pro_car mui-table-view-cell" id="${p.id}">
							<div class="mui-slider-right mui-disabled">
								<a class="mui-btn mui-btn-red garbage" data-id="${p.id}">删除</a>
							</div>
							<div class="mui-slider-handle">
								<div id="cart" class="cart_top">
									<span style="background-image: url('/static/wechat/img/cart/checked1.png');">
										<input class="selected" data-id="${p.id}" type="checkbox" onclick="selected(this)" name="test">
									</span>
									<img src="${p.pathname}" class="goto" href="/mobile/column/product_content?id=${p.pid}">
								</div>
								<div class="cart_box goto" href="/mobile/column/product_content?id=${p.pid}">
									<p class="overpl1"><span>${p.title}</span></p>
									<p class="c-999">
										装箱数:${p.number}<br>
										型号:${p.model}<br>
										单价:${p.price}<br>
									</p>
									<div>
										<!-- 是否可批发，是否满足批发数量 -->
										<span>￥ <b class="bprice" data-price="${p.price}" data-number="${p.number}" id="pricem${p.id}" data-id="${p.id}">${p.pricem}</b>/${p.spec == 1 ? '件' : '箱'}</span>
										<!-- <input class="j" type="hidden" value="${p.price}"> -->
									</div>
								</div>
								<span class="garbage" data-id="${p.id}"><i class="mui-icon fr iconfont">&#xe7a1;</i></span>
								<div class="mui-numbox fr numb" data-numbox-min="${p.min ? p.min : 1}" data-numbox-max="999">
									<button class="mui-btn mui-btn-numbox-minus" type="button">-</button>
									<input data-id="${p.id}" data-price="${p.price}" data-isw="${p.isw}" data-width="${p.width}" data-length="${p.length}" data-height="${p.height}" class="mui-input-numbox numbox jg_val" type="number" value="${p.num}" />
									<button class="mui-btn mui-btn-numbox-plus"  type="button">+</button>
								</div>		
							</div>
						</li>`
	}
	nodes(info)

	mui.init({
        swipeBack:true //启用右滑关闭功能
    });
    //释放 nav 底部导航 a 链接
    mui('.mui-tab-item').each(function () {
    	this.addEventListener('tap',function () {
    		var url = this.getAttribute('href');
    		window.location.href=url;
    	})
    });
 	
	 //数量改变后,改变数据库，若可批发，到达批发数量后，改成批发价格
    mui("body").on('change',".numbox",function(){
    	var that = this
    	var id = that.getAttribute("data-id")
    	var price = Number(that.getAttribute("data-price"))
    	var num = Number(that.value)
    	mui.get('/mobile/shopcar/changenum',{id:id,num:num},function(res){
    		if(res==1){
            	cartatine();         			
    		}else if (res==3){
    			mui.toast("库存不足")
    			
    		}
    	})
    })

	var chbAll=document.getElementById('asd');
        var chbs=document.querySelectorAll(
            "div span:first-child>input"
    );
    if(chbAll){
	    chbAll.onclick=function(){
	    	if (chbAll.checked) {
	    		chbAll.parentNode.style.backgroundImage = 'url(/static/wechat/img/cart/checked3.png)';
	    	}else {
	    		chbAll.parentNode.style.backgroundImage = 'url(/static/wechat/img/cart/checked1.png)';
	    	}
	        for(var i=0;i<chbs.length;i++){
	            chbs[i].checked=this.checked;
	           if (chbs[i].checked) {
	           	chbs[i].parentNode.style.backgroundImage = 'url(/static/wechat/img/cart/checked3.png)';
	           }else {
	           	chbs[i].parentNode.style.backgroundImage = 'url(/static/wechat/img/cart/checked1.png)';
	           }
	        }
	        cartatine();
	    }
    }
    function selected(e) {
    	// id = e.getAttribute("data-id")
    	var checked = 1;
		var inselected =e.parentNode;
		if (e.checked) {
			checked=1
			inselected.style.backgroundImage = 'url(/static/wechat/img/cart/checked3.png)';
		}else{
			checked=0
			inselected.style.backgroundImage = 'url(/static/wechat/img/cart/checked1.png)';
			chbAll.checked=false;
		}
     	cartatine();
	}

	function decimal(res) {
		let number = ~~(res * 1000)
	    let str = String(number)
	    let end = str.substring(str.length - 1)
	    number = end > 0 ? (number + 10 - end) / 1000 : number / 1000
	    return number
	}
	function brandTotal() {
		let totals = 0
		if (!$('.brand-wrap').length) return 0
		$('.brand-wrap').each(function () {
			let total = 0,
				fold = $(this).find('.price-total').attr('data-fold');
			$(this).find('.selected').each(function () {
				if (this.checked) {
					let price = $(this).parents('li.pro_car').find('.bprice').attr('data-price'),
						number = $(this).parents('li.pro_car').find('.bprice').attr('data-number'),
						num = $(this).parents('li.pro_car').find('.numbox').val();
					if (fold != 100) {
						price = decimal(decimal(price * fold) / 100)
					}
					total += decimal(price * num * number)
				}
			})
			totals += total
			$(this).find('.price-total').text('合计:' + decimal(total).toFixed(2))
		})
		return decimal(totals)
	}
	function cartatine() {
		var sum = 0;
	    var jg_num =0;
		var total = 0;
		var product_num = 0;
		var tj=0
		var brandTotals = brandTotal()
		mui(".pro_car").each(function () {
			
			if(this.getElementsByClassName("selected")[0].checked){
				// sum = sum + Number(this.getElementsByClassName("j")[0].value) * Number(this.getElementsByClassName("jg_val")[0].value);
				if (!$(this).parents('.brand-wrap').length) {
					sum = sum + Number(this.getElementsByClassName("bprice")[0].innerText) * Number(this.getElementsByClassName("jg_val")[0].value);
				}
				
				jg_num=jg_num + Number(this.getElementsByClassName("jg_val")[0].value);

				var length=this.getElementsByClassName("jg_val")[0].getAttribute('data-length')
				var width=this.getElementsByClassName("jg_val")[0].getAttribute('data-width')
				var height=this.getElementsByClassName("jg_val")[0].getAttribute('data-height')
				var vulum=parseFloat(length)*parseFloat(width)*parseFloat(height)*parseFloat(this.getElementsByClassName("jg_val")[0].value)/1000000
				tj+=vulum
			}
		})
		tj=tj.toFixed(2)
		// total += parseInt(sum);
		var newtotal =(sum + brandTotals).toFixed(2);
	    document.getElementById('product_total').innerHTML=newtotal;
	    document.getElementById('product_tj').innerHTML=tj;
	    var pro_car =document.getElementsByClassName('pro_car');
	    if (pro_car.length==0){
	    	document.getElementsByClassName('shopping_cart')[0].style.display='none'
	    	document.getElementsByClassName('settlement')[0].style.display='none'
	    	document.getElementsByClassName('noshopcar')[0].style.display='block'
	    }
	}

	// cartatine();

	mui('.garbage').each(function () {
    	var id = this.getAttribute('data-id');
	    this.addEventListener('tap', function() {
			var that=this
			that.disabled=true
			var btnArray = ['否', '是'];
			mui.confirm('确定要删除吗', '提示', btnArray, function(e) {
				if (e.index) {
					mui.ajax('/mobile/del',{
						type:'get',
						data:{id:id,table:'mt_order_car'},
						dataType:'json',
						timeout:1000,
						success: function(data){
	    				if (data) {
	    					mui.toast("删除成功~")
	    					var node=document.getElementById(id)
	    					var pnode=node.parentNode
	    					pnode.removeChild(node)
	    					if (pnode.getElementsByClassName("pro_car").length==0){
	    						if (pnode.className == 'brand-wrap') {
	    							pnode.remove()
	    						} else {
		    						var ppnode=pnode.parentNode
		    						ppnode.parentNode.removeChild(ppnode)
	    						}
	    					}
	    					cartatine()
	    				}else{
	    					mui.toast("删除失败,请重试!")
	    				}
	    				that.disabled=false
	    			},
					error: function(xhr, type){
						mui.toast("网络慢，请重试");
						that.disabled=false
					// 即使加载出错，也得重置
					}
					});
				}else{
					that.disabled=false
				}
			})
		});
    });
	if(document.getElementById('btn')){
	document.getElementById('btn').addEventListener('tap',function () {
		var pro_car =document.getElementsByClassName('pro_car');
		var arr3 =[];
		for (var i = 0; i < pro_car.length; i++) {
			var selected =document.getElementsByClassName('selected')[i];
			var garbage =pro_car[i].getAttribute('id');
			if (selected.checked) {
				arr3.push(garbage);
			}
		}
		if (arr3.length==0){
			mui.toast("请选择商品");
		}else{	
			window.location.href='/mobile/shopcar/sure?cid='+arr3
		}
	});
	}
</script>
